package com.jerry.gateway.zuul.service.impl;

import com.jerry.common.bean.User;
import com.jerry.gateway.zuul.service.AggregationService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import rx.Observable;

@Service
public class AggregationServiceImpl implements AggregationService {

    @Value("${provider.userUrl}")
    private String userUrl;

    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hystrix_user")
    public Observable<User> getUserById(Long id) {
        //创建一个观察者
        return Observable.create(observer -> {
            User user = restTemplate.getForObject(this.userUrl + "/user/get/" + id, User.class);
            observer.onNext(user);
            observer.onCompleted();
        });
    }

    @HystrixCommand(fallbackMethod = "hystrix_orderUser")
    public Observable<User> getOrderUserByUserId(Long id) {
        return Observable.create(observer -> {
            User user = restTemplate.getForObject(this.userUrl + "/user/get/" + id, User.class);
            observer.onNext(user);
            observer.onCompleted();
        });
    }

    /////////////////////////// 熔断处理 开始////////////////////////////////////
    public User hystrix_user(Long id, Throwable throwable) {
        System.out.println("进入回退方法，异常==="+throwable);

        User user = new User();
        user.setId(-1l);
        return  user;
    }

    public User hystrix_orderUser(Long id, Throwable throwable) {
        System.out.println("进入回退方法，异常==="+throwable);

        User user = new User();
        user.setId(-1l);
        return  user;
    }
    /////////////////////////// 熔断处理 结束////////////////////////////////////

}
